// ActionScript file
import Modules.NavigationDetails;
import Modules.NavigationInfo;
import Modules.Opportunity.OpportunityProductsDetail;
import Modules.PostLogin;
import Modules.Windows.CMDWindow;
import Modules.Windows.ValidationErrorWin;

import com.desidea.common.CommonClass;
import com.desidea.common.CustomFormatter;
import com.desidea.components.grid.SuperGrid;
import com.desidea.components.grid.SuperGridEvent;
import com.desidea.components.grid.button.SuperGridButton;
import com.desidea.components.spinner.BusySpinner;
import com.desidea.utils.DirtyChecker;
import com.desidea.utils.DisplayModeSetter;
import com.desidea.webservice.PartnerService;
import com.desidea.webservice.ProcessServiceRequestResultEvent;

import flash.events.MouseEvent;

import mx.controls.Alert;
import mx.controls.LinkButton;
import mx.controls.dataGridClasses.DataGridColumn;
import mx.core.Application;
import mx.events.CloseEvent;
import mx.events.ValidationResultEvent;
import mx.managers.PopUpManager;
import mx.rpc.events.FaultEvent;
import mx.utils.StringUtil;
import mx.validators.Validator;

private var _btnEditCancel:LinkButton;
private var _btnAddProduct:LinkButton;

private var _key:String = "";
private var _mode:String = "view";//Constants.MODE_ADD;
private var _modeSet:Boolean = false;
private var _creationCompleted:Boolean = false;
private var oppdetails:XML;
private var _accountGUID:String = "";
private var _doRecalculate:Boolean = false;
private var _ni:NavigationInfo = null;

public function get mode():String{
	return _mode;
}

public function set mode(value:String):void{
	this._mode = value;
	this._modeSet = true;
	
//	setScreenMode();
//	this.loadData();
}

public function get key():String{
	return _key;
}

public function set key(value:String):void{
	this._key = value;
}

public function get NavInfo():NavigationInfo{
	return _ni;
}

public function set NavInfo(value:NavigationInfo):void{
	this._ni = value;
}

public function get accountGUID():String{
	return _accountGUID;
}

public function set accountGUID(value:String):void{
	this._accountGUID = value;
}

private function typeSelectionChange():void{
	cmbContact.dataProvider = oppdetails.CONTACTS.entry.(@accountid == cmbAccountName.selectedItem.@id || @accountid == "0").(@active=="1" || @id == oppdetails.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT")) as XMLList;
	cmbContact.selectedIndex = 0;
	cmbContact.selectedItem = (oppdetails.CONTACTS.entry.(@id == oppdetails.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT"))[0]) as XML;
}

private function setScreenMode():void{
	if(!_creationCompleted) return;
	
	if(this.mode == SuperGridButton.MODE_VIEW || this.mode == SuperGridButton.MODE_VIEWICON){
		DisplayModeSetter.getInstance().setMode(this.frmOpportunityInfo,false);
		btnSubmit.enabled = false;
		_btnAddProduct.enabled = false;
		cmbAccountName.selectedItem = (oppdetails.ACCOUNTS.entry.(@id == oppdetails.RELATIONS.RELATION.(@type == "OPPORTUNITY_ACCOUNT"))[0]) as XML;
		this.lblTitle.text = "View Opportunity Detail";
	}else if(this.mode == SuperGridButton.MODE_EDIT){		//MODE_EDIT = create new
		DisplayModeSetter.getInstance().setMode(this.frmOpportunityInfo,true);
		cmbOppOwner.selectedItem = (oppdetails.USERS.entry.(@id == CommonClass.UserID.toString())[0]) as XML;
		btnSubmit.enabled = true;
		cmbAccountName.enabled = true;
		cmbOppOwner.enabled = false;
		_btnEditCancel.enabled = false;
		this.lblTitle.text = "New Opportunity";
	}
}

private function setGridMode():void{
//	(this.oppsProductsGrid.GridComponent.columns[0] as DataGridColumn).visible = (_btnAddProduct.enabled);
}

private function windowCreated():void{


	_btnEditCancel = new LinkButton();
	_btnEditCancel.label = "Edit";	
	_btnEditCancel.height = this.pnlOpportunityInfo.ToolBox.height - 2;
	_btnEditCancel.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('editdetails'); });
	this.pnlOpportunityInfo.ToolBox.addChild(_btnEditCancel);
	
	_btnAddProduct = new LinkButton();
	_btnAddProduct.label = "Add";	
	_btnAddProduct.height = this.pnlProductInfo.ToolBox.height - 2;
	_btnAddProduct.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('addproduct'); });
	this.pnlProductInfo.ToolBox.addChild(_btnAddProduct);

	if(	StringUtil.trim(this.key).length == 0){
		this.pnlProductInfo.height = 0;
		this.pnlProductInfo.visible = false;
	}
	
	this._creationCompleted = true;
	this.loadData();
	this.loadOpportunityProducts();

	this.oppsProductsGrid.addEventListener(SuperGridEvent.CLICKED, gridButtonColumnClicked);
	
	this.txtOppDesc.setFocus();
	
	_btnEditCancel.enabled = CommonClass.UserLoginInfo.CanCreateOpportunity;
	_btnAddProduct.enabled = CommonClass.UserLoginInfo.CanCreateOpportunity;//check

}


private function loadData():void{
	var params:String = "OPERATION=OPPORTUNITY_GETDETAILS" +
						"&PKID=" + escape(StringUtil.trim(this.key)) +
						"&OWNERID=" + CommonClass.UserID;
	
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForOpportunityDetails);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);
}

private function callForOpportunityDetails(event:ProcessServiceRequestResultEvent):void{
	oppdetails = XML(event.result);
	if(oppdetails.RESPONSE.RESULT == "E"){
		BusySpinner.getInstance().stop();
		Alert.show(oppdetails.RESPONSE.MESSAGE);
	}else if(oppdetails.RESPONSE.RESULT == 'S'){
		setDataOnControls(oppdetails);
		setScreenMode();
		typeSelectionChange();
		this.callLater(initializeForDirtyCheck);
	}
}

private function partnerServiceFaultHandler(event:FaultEvent):void{
	BusySpinner.getInstance().stop();
	Alert.show(event.fault.toString());
}

public function reloadOpportunityProducts():void{
	loadOpportunityProducts();
	_doRecalculate = true;	
}

private function loadOpportunityProducts():void{
	if(this.key.length>0){
		var params:String = "OPERATION=OPP_PROD_LIST" +
							"&PKID=" + escape(StringUtil.trim(this.key));
		
		var ws:PartnerService = new PartnerService();
		ws.addprocessServiceRequestEventListener(callForOpportunityProducts);
		ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
		ws.processServiceRequest(params);
	}
}
private function callForOpportunityProducts(event:ProcessServiceRequestResultEvent):void{
	var prods:XML = XML(event.result);
	if(prods.RESPONSE.RESULT == "E"){
		Alert.show(prods.RESPONSE.MESSAGE);
		_doRecalculate = false;
	}else if(prods.RESPONSE.RESULT == 'S'){
		this.oppsProductsGrid.dataProvider = prods;

		(this.oppsProductsGrid.GridComponent.columns[0] as DataGridColumn).visible = this.mode == (SuperGridButton.MODE_EDIT);

		setColumnWidths(this.oppsProductsGrid);

		if(_doRecalculate){
			recalculateValues();
		}
	}
}
private function recalculateValues():void{
	
	if(!isNaN(new Number(txtProbability.text))){
		txtProbability.text = (new Number(txtProbability.text)).toString();
	}
	
	if( probV.validate().type == ValidationResultEvent.INVALID){
		this.txtProbability.text = "0";
	}

	var dp:Object = oppsProductsGrid.GridComponent.dataProvider;

	var qty:Number = 0;
	var rev:Number = 0;

	for each(var row:Object in dp){
		qty+= new Number(row[2]);
		rev+= new Number(row[5]);
	}

	this.txtQuantityTotal.text = CustomFormatter.getInstance().converToNumberString(qty.toString());
	this.txtRevenue.text = CustomFormatter.getInstance().converToCurrencyString(rev.toString());
	
	var prob:Number = new Number(this.txtProbability.text);
	

	this.txtRevenueProbability.text = CustomFormatter.getInstance().converToCurrencyString((rev * prob/100).toFixed(2));
	_doRecalculate = false;
}

private function setDataOnControls(response:XML):void{
	this.key = response.PKID;
	
	cmbOppOwner.dataProvider = new XML(response.USERS).entry as XMLList;
	cmbOppOwner.selectedIndex = 0;
	cmbOppOwner.selectedItem = (response.USERS.entry.(@id == response.RELATIONS.RELATION.(@type == "OWNER"))[0]) as XML
	
	cmbOppType.dataProvider = new XML(response.OPPORTUNITYTYPES).entry as XMLList;
	cmbOppType.selectedIndex = 0;
	cmbOppType.selectedItem = (response.OPPORTUNITYTYPES.entry.(@id == response.OPPTYPEID)[0]) as XML;
	
	cmbAccountName.dataProvider = response.ACCOUNTS.entry as XMLList;
	cmbAccountName.selectedItem = (response.ACCOUNTS.entry.(@id == response.RELATIONS.RELATION.(@type == "OPPORTUNITY_ACCOUNT"))[0]) as XML;
	cmbAccountName.selectedIndex = (cmbAccountName.selectedIndex<0)?0:cmbAccountName.selectedIndex;
	
	cmbStatus.dataProvider = new XML(response.STATUS).entry as XMLList;
	cmbStatus.selectedIndex = 0;
	cmbStatus.selectedItem = (response.STATUS.entry.(@id == response.STATUSID)[0]) as XML
	
	cmbStage.dataProvider = new XML(response.OPPSTAGES).entry as XMLList;
	cmbStage.selectedIndex = 0;
	cmbStage.selectedItem = (response.OPPSTAGES.entry.(@id == response.OPPSTAGEID)[0]) as XML
	
	cmbResellerName.dataProvider = new XML(response.RESELLERACCOUNTS).entry as XMLList;
	cmbResellerName.selectedIndex = 0;
	cmbResellerName.selectedItem = (response.RESELLERACCOUNTS.entry.(@id == response.RESELLERNO)[0]) as XML
	
	cmbReferralSource.dataProvider = new XML(response.OPPREFERRALS).entry as XMLList;
	cmbReferralSource.selectedIndex = 0;
	cmbReferralSource.selectedItem = (response.OPPREFERRALS.entry.(@id == response.OPPREFERRALID)[0]) as XML
	
	CommonClass.setDataOnComponents(this.txtOppDesc, response);
	CommonClass.setDataOnComponents(this.txtRevenue, response);
	CommonClass.setDataOnComponents(this.txtProbability, response);
	CommonClass.setDataOnComponents(this.txtRevenueProbability, response);
	CommonClass.setDataOnComponents(this.txtQuantityTotal, response);
	CommonClass.setDataOnComponents(this.dtClose, response);
//	CommonClass.setDataOnComponents(this.dtMilestone, response);
	CommonClass.setDataOnComponents(this.txtApplication, response);
	CommonClass.setDataOnComponents(this.txtCompetitors, response);
	CommonClass.setDataOnComponents(this.txtNotes, response);
	
	this.txtRevenue.text = CustomFormatter.getInstance().converToCurrencyString(this.txtRevenue.text);
	this.txtRevenueProbability.text = CustomFormatter.getInstance().converToCurrencyString(this.txtRevenueProbability.text);
	this.txtQuantityTotal.text = CustomFormatter.getInstance().converToNumberString(this.txtQuantityTotal.text);

	cmbContact.dataProvider = new XML(response.CONTACTS).entry.(@accountid == cmbAccountName.selectedItem.@id || @accountid == "0").(@active=="1" || @id == response.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT")) as XMLList;
	cmbContact.selectedIndex = 0;
	cmbContact.selectedItem = (response.CONTACTS.entry.(@id == response.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT"))[0]) as XML

	if(this.accountGUID!=null && this.accountGUID.length >0){
		cmbAccountName.selectedItem = (response.ACCOUNTS.entry.(@guid == this.accountGUID.toUpperCase())[0]) as XML;
	}	
}


private function getPostData():String{

	this.txtRevenue.text = CustomFormatter.getInstance().converToCurrencyString(this.txtRevenue.text,false);
	this.txtRevenueProbability.text = CustomFormatter.getInstance().converToCurrencyString(this.txtRevenueProbability.text,false);
	this.txtQuantityTotal.text = CustomFormatter.getInstance().converToNumberString(this.txtQuantityTotal.text,false);

	var postData:String = new String();
	postData += "OPPORTUNITYID=" + (oppdetails.OPPORTUNITYID.toString())		+ "&";
	postData += "OPPORTUNITYGUID=" + (oppdetails.OPPORTUNITYGUID.toString())	+ "&";

//	postData += "OPPREFERRALID=" + (oppdetails.OPPREFERRALID.toString())		+ "&";
	postData += "NOTEID=" + (oppdetails.NOTEID.toString())						+ "&";
	postData += "USERID=" + (CommonClass.UserID)								+ "&";
				
	postData += (CommonClass.preparePostString(this.txtOppDesc))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbOppType))				+ "&";
	postData += (CommonClass.preparePostString(this.txtRevenue))				+ "&";
	postData += (CommonClass.preparePostString(this.txtProbability))			+ "&";
	postData += (CommonClass.preparePostString(this.txtRevenueProbability))		+ "&";
	postData += (CommonClass.preparePostString(this.txtQuantityTotal))			+ "&";
	postData += (CommonClass.preparePostString(this.dtClose))					+ "&";
//	postData += (CommonClass.preparePostString(this.dtMilestone))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbStatus))					+ "&";
	postData += (CommonClass.preparePostString(this.txtApplication))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbStage))					+ "&";
	postData += (CommonClass.preparePostString(this.txtCompetitors))			+ "&";
	postData += (CommonClass.preparePostString(this.txtNotes))					+ "&";
	postData += (CommonClass.preparePostString(this.cmbResellerName))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbReferralSource))			+ "&";

	postData += (CommonClass.preparePostString(this.cmbOppOwner))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbContact))				+ "&";
	postData += (CommonClass.preparePostString(this.cmbAccountName));
	
	this.txtRevenue.text = CustomFormatter.getInstance().converToCurrencyString(this.txtRevenue.text);
	this.txtRevenueProbability.text = CustomFormatter.getInstance().converToCurrencyString(this.txtRevenueProbability.text);
	this.txtQuantityTotal.text = CustomFormatter.getInstance().converToNumberString(this.txtQuantityTotal.text);

	return postData;	
}

private function saveData(action:String, data:String=""):void{
	BusySpinner.getInstance().play(Application.application.ModuleCvs);
	var params:String = "OPERATION=OPPORTUNITY_UPDATEDETAILS" +
						(data.length>0?"&":"") +data;
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForUpdateOppsDetails);
	ws.processServiceRequest(params);
}


private function callForUpdateOppsDetails(event:ProcessServiceRequestResultEvent):void{
	var response:XML = XML(event.result);
	if(response.RESPONSE.RESULT == "S"){
		DirtyChecker.getInstance().resetDirtyChecker();

		if(CommonClass.NextEvent != null && CommonClass.NextEvent is Button)
			(CommonClass.NextEvent as Button).dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		else{
			var ni:NavigationInfo = this.NavInfo.copy();
			ni.destinationNavObj.pkID = this.key;
			(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate( ni);
		}
	}else{
		BusySpinner.getInstance().stop();
		Alert.show( String(response.RESPONSE.MESSAGE) );	
	}	
}


private function init():void{
	this.txtNotes.linkTextInput.visible = false;
	this.txtNotes._RichTextEditor_VRule2.visible = false;
}

private function onClick(mode:String):void{
	switch(mode){
		case "editdetails":
			DisplayModeSetter.getInstance().setMode(this.frmOpportunityInfo,true);
			btnSubmit.enabled = true;
			cmbAccountName.enabled = false;
			cmbOppOwner.enabled = false;
			_btnEditCancel.enabled = false;
			_btnAddProduct.enabled = true;
			(this.oppsProductsGrid.GridComponent.columns[0] as DataGridColumn).visible = true;
			this.lblTitle.text = "Edit Opportunity Detail";
			this.mode = SuperGridButton.MODE_EDIT;
			break;
		case "addproduct":
			showDetail(SuperGridButton.MODE_EDIT,"");
			break;
	}
}

private function showDetail(mode:String, key:String=""):void{
	
	var cd:OpportunityProductsDetail = new OpportunityProductsDetail();
	cd.key = key;
	cd.caller = this;
	cd.opportunityGUID = this.key;
	
	PopUpManager.addPopUp(cd,this,true);
	PopUpManager.centerPopUp(cd);
}

private function buttonClick(eventType:String):void{
	switch(eventType){
		case "save":
			handleSubmitClick();
			break;
		case "cancel":
			handleCancelClick();
			break;
		default:
			Alert.show( "Yet to Implement : " + eventType);
	}
}

private function handleCancelClick():void{
	(this.parentDocument as CMDWindow).NavInfo = null;
	CommonClass.NextEvent = null;
	
	if(this.NavInfo!=null && this.NavInfo.sourceNavObj!=null){
		var src:NavigationDetails = (this.NavInfo.previousLink==null?null:this.NavInfo.previousLink.sourceNavObj.copy());//this.NavInfo.destinationNavObj.copy();
		var dst:NavigationDetails = this.NavInfo.sourceNavObj.copy();
		var ni:NavigationInfo = new NavigationInfo(src,dst);
		ni.previousLink = (this.NavInfo.previousLink == null? null:this.NavInfo.previousLink.previousLink);
		(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(ni);
	}else{
		(this.parentDocument as CMDWindow).loadModule();
	}
}

private function handleSubmitClick():void{
	if(validate()){
		saveData("", getPostData());
	}else{
		CommonClass.NextEvent = null;
	}
}
private function validate():Boolean{
	var v:Array = new Array();
	v.push(descV,oppTypeV,accNameV, contactV);
	v.push(revnV,probV,revnProbV);
	v.push(qtyV, closedtV);
	v.push(statusV, stageV, refsrcV);
	
	var result:Array = Validator.validateAll(v);

	if(result.length>0){
		var vWin:ValidationErrorWin = new ValidationErrorWin();
		vWin.Messages = result;
		vWin.title = "Save : Contact Details";
		
		PopUpManager.addPopUp(vWin,this,true);
		PopUpManager.centerPopUp(vWin);
		return false;
	}
	return true;
}

private function setColumnWidths(grid:SuperGrid):void{
	CommonClass.setColumnWidth(grid, 1, 180);
	CommonClass.setColumnWidth(grid, 2, 90,"right");
	CommonClass.setColumnWidth(grid, 3, 90,"right");
	CommonClass.setColumnWidth(grid, 4, 90,"right");
	CommonClass.setColumnWidth(grid, 5, 90,"right");
}


private function gridButtonColumnClicked(event:SuperGridEvent):void{
	handleGridButtonClick(event);
}

private function handleGridButtonClick(event:SuperGridEvent, moduleCode:String = null):void{
	var mode:String =  String(event.data.linkId).toLowerCase();
	
	if(mode == SuperGridButton.MODE_EDIT || mode == SuperGridButton.MODE_VIEW || mode == SuperGridButton.MODE_VIEWICON){
		showDetail(mode, event.data.data["key"].toString());
	}else{
		Alert.show("Mode : " + mode + " not handled");
	}
	
}

private function initializeForDirtyCheck():void{
	DirtyChecker.getInstance().setInitialControl(this);
	BusySpinner.getInstance().stop();
}

public function promptToSave():void{
	Alert.buttonWidth = 110;
	var yesNoCancelAlert: Alert = Alert.show("Do you want to save before exiting?", "Save",Alert.YES | Alert.NO | Alert.CANCEL, Application.application.ModuleCvs,performAlertAction);
}

private function performAlertAction(event:CloseEvent):void{
	if(event.detail == Alert.YES){
		handleSubmitClick();
	}else if(event.detail == Alert.NO){
		DirtyChecker.getInstance().resetDirtyChecker();
		if(CommonClass.NextEvent != null && CommonClass.NextEvent is Button)
			(CommonClass.NextEvent as Button).dispatchEvent(new MouseEvent(MouseEvent.CLICK));
		else
			handleCancelClick();
	}else{
		// PERFORM NO ACTION - STAY BACK TO THE PAGE
	}
}